﻿//
//  Monkey Manager
//  Copyright (C) 2012 Victor Tereschenko
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
//     
// ========================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

using ManagerDB;

namespace MMDescEditor
{
    public partial class Edit : Form
    {
        public Edit()
        {
            InitializeComponent();
        }

        private void openButton_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            ofd.Filter = "MMDesc|*.mmdesc||";
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                show(ofd.FileName);
            }
        }

        string mFileName;
        StoredFile mFile;
        void show(string fileName)
        {
            mFileName = fileName;
            mFile = DescriptionFileReader.Read(fileName);
            update();
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            mFile.Title = nameTextBox.Text;
            mFile.Description = descTextBox.Text;
            mFile.Original = originalNamTextBox.Text;
            if (dateTimePicker.Value.Year > 1900)
            {
                mFile.Year = dateTimePicker.Value.Year;
                mFile.Month = dateTimePicker.Value.Month;
                mFile.Day = dateTimePicker.Value.Day;
            }

            DescriptionFileWriter writer = new DescriptionFileWriter(mFile);
            writer.Save(mFileName);
        }

        private void removeFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (int index in filesListView.SelectedIndices)
            {
                mFile.Files.Remove(mFile.Files[index]);
                break;
            }
            updateFiles();
        }

        private void addFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (string file in ofd.FileNames)
                {
                    var description = getDescription(file);
                    if (!mFile.Files.Exists(f => f.ID.TTH == description.ID.TTH && f.ID.Size == description.ID.Size))
                        mFile.Files.Add(description);
                }
            }
            updateFiles();
        }

        static string getTechInfo(string filePath)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mediainfo", "MediaInfo.exe");
            if (!File.Exists(path))
                return null;
            var mediaInfo = new System.Diagnostics.ProcessStartInfo(path, string.Format("--f \"{0}\"", filePath));
            mediaInfo.UseShellExecute = false;
            mediaInfo.RedirectStandardOutput = true;
            var process = System.Diagnostics.Process.Start(mediaInfo);
            return process.StandardOutput.ReadToEnd();
        }

        private static FileDescription getDescription(string file)
        {
            var fileInfo = new FileInfo(file);
            var description = new FileDescription();
            description.ID.TTH = MonkeyManager.Hasher.GetTTH(file);
            description.ID.Size = fileInfo.Length;
            description.TechInfo = getTechInfo(file);
            return description;
        }

        private void update()
        {
            if (mFile == null)
                return;
            nameTextBox.Text = mFile.Title;
            descTextBox.Text = mFile.Description;
            originalNamTextBox.Text = mFile.Original;
            if (mFile.Year > 0)
                dateTimePicker.Value = new DateTime((int)mFile.Year, (int)mFile.Month, (int)mFile.Day);
            else
                dateTimePicker.Value = new DateTime(1900, 1, 1);
            updateFiles();
            updateImages();
        }

        private void updateImages()
        {
            imagesListView.Items.Clear();
            foreach (FileID images in mFile.Images)
            {
                var listItem = new ListViewItem(images.TTH);
                imagesListView.Items.Add(listItem);
            }
        }

        private void updateFiles()
        {
            filesListView.Items.Clear();
            foreach (FileDescription file in mFile.Files)
            {
                var listItem = new ListViewItem(file.ID.TTH);
                filesListView.Items.Add(listItem);
            }
        }

        private void addImagesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (string file in ofd.FileNames)
                {
                    var fileInfo = new FileInfo(file);
                    FileID fileId = new FileID();
                    fileId.TTH = MonkeyManager.Hasher.GetTTH(file);
                    fileId.Size = fileInfo.Length;
                    if (!mFile.Images.Exists(f => f.TTH == fileId.TTH && f.Size == fileId.Size))
                        mFile.Images.Add(fileId);
                }
            }
            updateImages();
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (int index in imagesListView.SelectedIndices)
            {
                mFile.Images.Remove(mFile.Images[index]);
                break;
            }
            updateImages();
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                mFile = new StoredFile();
                mFile.Title = Path.GetFileNameWithoutExtension(ofd.FileName);
                mFile.Files.Add(getDescription(ofd.FileName));
                mFileName = Path.ChangeExtension(ofd.FileName, ".mmdesc");
            }
            update();
        }
    }
}
